package com.lingshi.shopping_manager_api.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.lingshi.shopping_common.entity.Admin;
import com.lingshi.shopping_common.exception.BusCodeEnum;
import com.lingshi.shopping_common.result.BaseResult;
import com.lingshi.shopping_common.service.IAdminService;
import com.lingshi.shopping_manager_api.service.ILoginService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IAdminService adminService;

    @Override
    public BaseResult login(String username, String password) {
        Admin admin = adminService.findByAdminName(username);

        // 判断admin对象不为空
        if(Objects.nonNull(admin)){
            //比对加密的密码
            String md5Password = SaSecureUtil.md5(password);
            //比较用户输入的密码
            if(md5Password.equals(admin.getPassword())){
                //sa-token登录
                StpUtil.login(username);
                //获取token，返回给前端
                String tokenValue = StpUtil.getTokenValue();

                return BaseResult.success(tokenValue);
            }
        }

        //抛出异常
        return BaseResult.error(BusCodeEnum.LOGIN_ERROR.getMessage());

    }
}
